import { message } from 'antd';
import E from 'wangeditor';
import React, { useEffect, useRef, useState } from 'react';
import { request } from '../../app'

interface Props {
  initialValue?: string,
  valueChange: (html: string) => void,
}

const TextEditor: React.FC<Props> = (props) => {
  const { initialValue, valueChange } = props;
  const initEditor = () => {
    const editor = new E('#div1');

    //editor.config.zIndex = 100
    editor.config.uploadImgServer = request.imgUrl + '/api/Upload/Upload'
    editor.config.uploadImgMaxLength = 1
    editor.config.onchange = valueChange;
    editor.config.customUploadImg = (files: any, insert: any) => {
      console.log(files)
      if (files[0]) {
        const formData = new window.FormData()
        formData.append('file', files[0], 'cover.jpg')
        fetch(request.imgUrl + '/api/Upload/Upload', {
          method: 'POST',
          body: formData
        }).then((res) => {
          return res.json()
        }).then((res) => {
          const data = res.resultData
          if (data) {
            insert(data.resourceUrl)
          } else {
            console.log(data.msg)
          }
        })
      } else {
        message.info('')
      }
    }

    editor.config.menus = [
      'head', // 标题
      'bold', // 粗体
      'fontSize', // 字号
      'fontName', // 字体
      'italic', // 斜体
      'underline', // 下划线
      'strikeThrough', // 删除线
      'foreColor', // 文字颜色
      'backColor', // 背景颜色
      'link', // 插入链接
      'list', // 列表
      'justify', // 对齐方式
      'quote', // 引用
      'emoticon', // 表情
      'image', // 插入图片
      'table', // 表格
      'video', // 插入视频
      'code', // 插入代码
      'undo', // 撤销
      'redo' // 重复
    ];

    editor.create();
    if (initialValue) {
      editor.txt.html(initialValue);
    }
  }

  useEffect(() => {
    initEditor();
  }, [])

  return (<div id="div1" />)
}

export default TextEditor;
